package com.clouddot.baipai.model;


import android.util.Log;

import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by wxy on 2018/4/8.
 */

public class netConnect {
    public static netConnect instance;

    public static netConnect getInstance(){
        if(instance == null){
            instance = new netConnect();
        }
        return instance;
    }
    private OkHttpClient okHttpClient;

    public netConnect(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        okHttpClient = builder.build();
    }

    public String getConnect(String flag , String url) {
        String str = "";
        Request request = null;
        Response response = null;
        Env.info(flag+"  ---->>  "+url);
        try {
            if(Env.getAppContext().session == null){
                request = new Request.Builder().url(url).build();
                response = okHttpClient.newCall(request).execute();
                Headers headers = response.headers();
                Log.d("info_headers", "header " + headers);
                List<String> cookies = headers.values("Set-Cookie");
                String session = cookies.get(0);
                Env.getAppContext().session = session.substring(0, session.indexOf(";"));
            }else {
                request = new Request.Builder().addHeader("cookie",Env.getAppContext().session).url(url).build();
                response = okHttpClient.newCall(request).execute();
            }
            if(response.isSuccessful()){
                str = response.body().string();

                Env.info(flag+"---->>结果 :"+ str + "\n");
            }
        } catch (IOException e) {
            Env.error(Environment.getInstance().fileUtil.Errorinfo(e)+"\n访问的连接是--："+url );
            return "error";
        }

        return str;
    }

    public String getConnect2(String flag ,String url) {
        String str = "";
        Request request = null;
        Response response = null;
        Env.info(flag+"  ---->>  "+url);


        try {
            request = new Request.Builder().url(url).build();
            response = okHttpClient.newCall(request).execute();
            if(response.isSuccessful()){
                str = response.body().string();
                Env.info(flag+"---->>结果 :"+ str + "\n");

            }
        } catch (IOException e) {
            Env.error(Environment.getInstance().fileUtil.Errorinfo(e));
            return "error";
        }

        return str;
    }

    public String getWeather(String url){
        Env.info(url);
        Request request = null;
        Response response = null;
        try {
            request = new Request.Builder().url(url).build();
            response = okHttpClient.newCall(request).execute();
            if(response.isSuccessful()){
                return response.body().string();
            }
        } catch (IOException e) {
            Env.error(Environment.getInstance().fileUtil.Errorinfo(e));

            return  "error";

        }
        return "";
    }
    /**
     * post表单请求提交,获取json字符串
     *
     * @param url
     * @param params
     */
    public Call postComplexForm(String url, Map<String, String> params) {

        FormBody.Builder builder = new FormBody.Builder();//表单对象，包含以input开始的对象，以html表单为主
        //把map集合中的参数添加到FormBody表单中.
        if (null != params && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
            RequestBody requestBody = builder.build();//创建请求体
            Request request =  new Request.Builder().url(url)
                    .addHeader("Connection", "close")
                    .post(requestBody).build();
            Call call = okHttpClient.newCall(request);
            return call;
        }
        return null;
    }

    public Call postNet(String url, Map<String, Object> params) {

        if (null != params && !params.isEmpty()) {
            Gson gson = new Gson();
            String json = gson.toJson(params);
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
             RequestBody requestBody = RequestBody.create(JSON, json);
            Request request =  new Request.Builder().url(url)
                    .addHeader("Connection", "close")
                    .post(requestBody).build();
            Call call = okHttpClient.newCall(request);
            return call;
        }
        return null;
    }
}
